Signup/Sign In

PHP for and foreach Loop

In this tutorial we will learn about for and foreach loops which are also used to implement looping in PHP.

To understand what are loops and how they work, we recommend you to go through the previous tutorial.


PHP for Loop

The for loop in PHP doesn't work like while or do...while loop, in case of for loop, we have to declare beforehand how many times we want the loop to run.

Syntax:

<?php
for(initialization; condition; increment/decrement)
{
    /* 
        execute this code till the  
        condition is true
    */
}
?>

The parameters used have following meaning:

  1. initialization: Here we initialize a variable with some value. This variable acts as the loop counter.
  2. condition: Here we define the condition which is checked after each iteration/cycle of the loop. If the condition returns true, then only the loop is executed.
  3. increment/decrement: Here we increment or decrement the loop counter as per the requirements.

How for loop works in Php


Time for an Example

Again, lets try to print numbers from 1 to 10, this time we will be using the for loop.

<?php

for($a = 1; $a <= 10; $a++)
{
    echo "$a <br/>";
}
?>

1 2 3 4 5 6 7 8 9 10


Nested for Loops

We can also use a for loop inside another for loop. Here is a simple example of nested for loops.

<?php

for($a = 0; $a <= 2; $a++)
{
    for($b = 0; $b <= 2; $b++)
    {
        echo "$b $a 
"; } } ?>

0 0 1 0 2 0 0 1 1 1 2 1 0 2 1 2 2 2


PHP foreach Loop

The foreach loop in PHP is used to access key-value pairs of an array. This loop only works with arrays and you do not have to initialise any loop counter or set any condition for exiting from the loop, everything is done implicitly(internally) by the loop.

Syntax:

<?php
foreach($array as $var)
{
    /* 
        execute this code for all the
        array elements
        
        $var will represent all the array
        elements starting from first element, 
        one by one
    */
}
?>

Here is a simple example.

<?php

$array = array("Jaguar", "Audi", "Mercedes", "BMW");

foreach($array as $var)
{
    echo "$var <br/>";
}

?>

Jaguar Audi Mercedes BMW

We will learn about arrays in detail in upcoming tutorial.